/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ret;
        if(root==nullptr)
            return ret;
        queue<TreeNode*> q;
        q.push(root);
        ret.push_back(root->val);
        while(q.size())
        {
            int sz=q.size();
            vector<int> t;
            while(sz--)
            {
                TreeNode* u=q.front();
                q.pop();
                if(u->left)
                {
                    q.push(u->left);
                    t.push_back(u->left->val);
                }
                if(u->right)
                {
                    q.push(u->right);
                    t.push_back(u->right->val);
                }
            }
            if(t.size())
                ret.push_back(t.back());
        }
        return ret;
    }
};
